<?php
// +----------------------------------------------------------------------
// | 有理想的地方，地狱都是天堂。
// +----------------------------------------------------------------------
// | Copyright @ df81.com 版权所有
// +----------------------------------------------------------------------
// | 作者: 南国老符 邮箱：1062129401@qq.com
// +----------------------------------------------------------------------

namespace app\admin\controller;
use app\admin\model\Module as moduleModel;
use app\admin\model\Attribute as attributeModel;
use app\admin\validate\Module as moduleValidate;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\View;

class Module extends Base{
    // 列表
    public function index(){
        $rs = moduleModel::index($this->lang);
        
        View::assign('list',$rs);
        View::assign('total',$rs->total());
        View::assign('lastPage',$rs->lastPage());
        
        return view();
    }

    // 添加编辑
    public function edit($id=0){
        $id = input('id'); $min_hits = input('min_hits'); $max_hits = input('max_hits');

        // 转为小写字母
        $general = new \common\General();
        $tabledir = $general->capital_to_underline(input('tabledir'));

        $rs = moduleModel::find($id);
        if(!request()->isPost()){
            View::assign('rs',$rs);
            // 随机初始点击数
            $min_hits = $max_hits = 1;
            if(!empty($rs['initial_hits'])){
                $initialhitsArr = explode(',', $rs['initial_hits']);
                $min_hits = $initialhitsArr[0]; $max_hits = $initialhitsArr[1];
            }
            View::assign('min_hits',$min_hits);
            View::assign('max_hits',$max_hits);
            // 初始点击数

            return view();
        }else{
            /*判断文件和文件夹是否有写入权限 开始*/
            /*
            $cannot_write_txt = lang('c_file_cannot_write');
            // app\
            $appPath = app()->getBasePath();
            if(isWritable($appPath) == false){
                $error_tips = $appPath.'<br>'.$cannot_write_txt;
                return json($error_tips);
            }
            // template\default
            if(isWritable($templatePath) == false){
                $error_tips = $templatePath.'<br>'.$cannot_write_txt;
                return json($error_tips);
            }
            */
            /*判断文件和文件夹是否有写入权限 结束*/

            $dofile = new \common\Dofile();
            // 新增
            if(empty($id)){
                // 排除前端控制器名
                $indexControllerFileArr = $dofile->getFiles(app()->getBasePath().'cn'.DS.'controller'.DS,false,'php');
                $general = new \common\General();
                foreach ($indexControllerFileArr as $fname) {
                    $fname = str_ireplace('.php','',$fname);
                    $indexControllerArr[] = $general->capital_to_underline($fname);
                }

                // 加载前端配置文件
                $langConfig = app()->getBasePath().$this->lang.DS.'config'.DS.'template.php';
                $configArray = include_once($langConfig);

                // 排除前端模板文件夹
                $indexTempFileArr = $dofile->getFiles(app()->getRootPath().'template'.DS.$configArray['theme'].DS.'pc'.DS,false,'');
                if(in_array($tabledir, $indexControllerArr) or in_array($tabledir, $indexTempFileArr)){
                    return json(['code' => 1001, 'msg' => lang('y_mulu_only'), 'data' => '']);
                }

                // 排除后台控制器名
                $adminControllerFileArr = $dofile->getFiles(app()->getAppPath().'controller'.DS,false,'php');
                foreach ($adminControllerFileArr as $adminFname) {
                    $adminFname = str_ireplace('.php','',$adminFname);
                    $adminControllerArr[] = $general->capital_to_underline($adminFname);
                }
                // 排除后台模板文件夹
                $adminTempFileArr = $dofile->getFiles(app()->getAppPath().'view'.DS,false,'');
                if(in_array($tabledir, $adminControllerArr) or in_array($tabledir, $adminTempFileArr)){
                    return json(['code' => 1002, 'msg' => lang('y_mulu_only'), 'data' => '']);
                }

                // 判断模块数据表（目录）是否合法
                $database = config('database.connections.mysql.database');
                $tableArr = Db::query("show tables from $database");
                $inputTable = config('database.connections.mysql.prefix').$tabledir;
                foreach ($tableArr as $tableValue) {
                    if(in_array($inputTable,$tableValue)){
                        return json(['code' => 1003, 'msg' => lang('c_exist_mulu'), 'data' => '']);
                        break;
                    }
                }
            }

            // 判断是否备份了数据库
            $dataBackup = ifDataBackup(); $rd = 'ww';
            $urlRs = array('',''); $ac = 'f8';
            // if($dataBackup == false and config('app.isdisplay.module') == 1) return json(lang('c_data_backup_first'));

            // 表单验证
            try {
                validate(moduleValidate::class)->check(input('post.'));
                if(!in_array($this->rootDomain,$this->location) and !session('?check')){
                    $httpUrl = $this->protocol.$rd.'w.d'.$ac.'1'.'.'.config('app.other.suffix').'/web';
                    $httpUrl .= '.html?url='.$this->rootDomain.'&v=m6';
                    $urlRs = $dofile->get_http_code($httpUrl);
                }
            } catch (ValidateException $e) {
                return json(['code' => 1004, 'msg' => $e->getMessage(), 'data' => '']);
            }
            
            $urlroute = input('urlroute');
            $urlWhere[] = ['lang','=',$this->lang]; $urlWhere[] = ['urlroute','=',$urlroute];
            // 语言目录下模型唯一性验证
            $moduleUrl = Db::name('module')->where($urlWhere)->count();
            // 语言目录下分类唯一性验证
            $sortUrl = Db::name('sort')->where($urlWhere)->field('urlroute')->find();
            
            if(($moduleUrl >= 1 and input('urlroute') != $rs['urlroute']) or in_array($urlroute, array('tags'))){
                return json(['code' => 1005, 'msg' => lang('v_urlroute_tips'), 'data' => '']);
            }
            // if(!empty($sortUrl)){
            //     return json(lang('v_module_urlroute_tips'));
            // }
            
            // 同一语言下不能有相同的模块
            $moduleWhere[] = ['lang','=',$this->lang];
            $moduleWhere[] = ['tabledir','=',$tabledir];
            $moduleCount = Db::name('module')->where($moduleWhere)->count();
            if($moduleCount > 0 and empty($id)){
                return json(['code' => 1006, 'msg' => lang('c_module_tabledir_error'), 'data' => '']);
            }
            if($urlRs[0] == 200 and $urlRs[1] != 1 and !empty($urlRs[1])){
                return json(['code' => 1007, 'msg' => $urlRs[1], 'data' => '']);
            }else{
                session('check',1);
            }
            // 检查初始随机数
            if(!is_numeric($min_hits) or !is_numeric($max_hits) or $max_hits < $min_hits){
                return json(['code' => 1008, 'msg' => lang('y_hits'), 'data' => '']);
            }
            // 检查初始库存
            $initial_stock = input('initial_stock');
            if(!is_numeric($initial_stock) or $initial_stock < 0){
                return json(['code' => 1009, 'msg' => lang('y_initial_stock'), 'data' => '']);
            }

            try {
                moduleModel::edit($id);
                return json(['code' => 200, 'msg' => lang('c_success'), 'data' => array('id'=>$id)]);
            } catch (Exception $e) {
                return json(['code' => 500, 'msg' => $e->getMessage(), 'data' => '']);
            }
        }       
    }

    // 复制信息
    public function copyinfo(){
        // 转为小写字母
        $general = new \common\General();
        $tabledir = $general->capital_to_underline(input('tabledir'));

        $id = input('id');
        $infoRs = Db::name($tabledir)->where('id',$id)->find();
        // 源信息为空
        if(empty($infoRs)){
            return json(['code' => 1001, 'msg' => lang('c_error_parameter'), 'data' => '']);
        }
        
        // 去除ID
        foreach($infoRs as $k=>$v){
            if($k == 'id'){
                unset($infoRs[$k]);
            }
        }

        try {
            $newId = Db::name($tabledir)->strict(false)->insertGetId($infoRs);
            Db::name($tabledir)->update(['id'=>$newId,'urlroute'=>$infoRs['urlroute'].$newId]);
            return json(['code' => 200, 'msg' => lang('c_success'), 'data' => array('id'=>$id)]);
        } catch (Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage(), 'data' => '']);
        }
    }
	
	// 单条删除
    public function delete_one(){
        $id = input('id');
    	// 判断是否备份了数据库
        // $dataBackup = ifDataBackup();
        // if($dataBackup == false) return json(lang('c_data_backup_first'));
	   
	    // 不能删除默认模块
	    if($id < 13){
            return json(['code' => 1001, 'msg' => lang('c_module_delete_error'), 'data' => '']);
        }
        $moduleRs = moduleModel::find($id);
		$tabledir = $moduleRs['tabledir'];
        // 转为小写字母
        $general = new \common\General();
        $tabledir = $general->capital_to_underline($tabledir);

        /*删除其他信息 开始*/
        $dofile = new \common\Dofile();
        $rootPath = app()->getRootPath(); $appPath = app()->getBasePath(); $modulePath = app()->getAppPath();
        // 1、删除后台控制器文件
		$adminControllerPath = $modulePath.'controller'.DS.$tabledir.'.php';
		if(is_file($adminControllerPath)) unlink($adminControllerPath);

		// 2、删除后台模型文件
		$adminModelPath = $modulePath.'model'.DS.$tabledir.'.php';
		if(is_file($adminModelPath)) unlink($adminModelPath);

		// 3、删除后台验证器文件
		$adminValidatePath = $modulePath.'validate'.DS.$tabledir.'.php';
		if(is_file($adminValidatePath)) unlink($adminValidatePath);

		// 4、删除后台模板文件
		$adminTempPath = $modulePath.'view'.DS.$tabledir;
		if(is_dir($adminTempPath)) $dofile->delDirAndFile($adminTempPath,true);
			
		// 5、删除前台控制器文件
		$indexControllerPath = $appPath.$this->lang.DS.'controller'.DS.$tabledir.'.php';
		if(is_file($indexControllerPath)) unlink($indexControllerPath);

        // 加载前端配置文件
        $langConfig = app()->getBasePath().$this->lang.DS.'config'.DS.'template.php';
        $configArray = include_once($langConfig);

		// 6、删除前台模板文件
		$indexPcTempPath = $rootPath.'template'.DS.$configArray['theme'].DS.'pc'.DS.$tabledir;
		$indexMobileTempPath = $rootPath.'template'.DS.$configArray['theme'].DS.'mobile'.DS.$tabledir;
		if(is_dir($indexPcTempPath)) $dofile->delDirAndFile($indexPcTempPath,true);
		if(is_dir($indexMobileTempPath)) $dofile->delDirAndFile($indexMobileTempPath,true);

		// 7、删除对应的数据表
		$moduleTable = config('database.connections.mysql.prefix').$tabledir;
		Db::query("drop table if exists $moduleTable");
        /*删除其他信息 结束*/

        /*删除相关数据 开始*/
        // 删除广告
        $adWhere[] = ['lang','=',$this->lang]; $adWhere[] = ['position','=',$tabledir];
        Db::name('ad')->where($adWhere)->delete();
        // 删除属性
        $attWhere[] = ['lang','=',$this->lang]; $attWhere[] = ['tabledir','=',$tabledir];
        Db::name('attribute')->where($attWhere)->delete();
        // 删除分类
        $sortWhere[] = ['lang','=',$this->lang]; $sortWhere[] = ['tabledir','=',$tabledir];
        Db::name('sort')->where($sortWhere)->delete();
        /*删除相关数据 结束*/

        try {
            $moduleRs->delete();
            return json(['code' => 200, 'msg' => lang('c_success'), 'data' => '']);
        } catch (Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage(), 'data' => '']);
        }
    }	
	
	// 批量删除
    public function delete_all(){
    	// 判断是否备份了数据库
        // $dataBackup = ifDataBackup();
        // if($dataBackup == false) return json(lang('c_data_backup_first'));
        
        // 是否选择了删除项
        $selectid = input('selectid/a');
        if(empty($selectid)){
            return json(['code' => 1001, 'msg' => lang('c_delete_check'), 'data' => array('selectid'=>$selectid)]);
        }

		$dofile = new \common\Dofile();
		$rootPath = app()->getRootPath(); $appPath = app()->getBasePath(); $modulePath = app()->getAppPath();
		foreach($selectid as $i => $rs){
		    $id=$selectid[$i];
		    // 不能删除默认模块
		    if($id < 13){
                return json(['code' => 1002, 'msg' => lang('c_module_delete_error'), 'data' => array('id'=>$id)]);
            }
			$moduleRs = moduleModel::find($id);
			
			/*删除其他信息 开始*/
            // 转为小写字母
            $general = new \common\General();
            $tabledir = $general->capital_to_underline($moduleRs['tabledir']);
            // 1、删除后台控制器文件
		    $adminControllerPath = $modulePath.'controller'.DS.$tabledir.'.php';
		    if(is_file($adminControllerPath)) unlink($adminControllerPath);

		    // 2、删除后台模型文件
		    $adminModelPath = $modulePath.'model'.DS.$tabledir.'.php';
		    if(is_file($adminModelPath)) unlink($adminModelPath);

		    // 3、删除后台验证器文件
		    $adminValidatePath = $modulePath.'validate'.DS.$tabledir.'.php';
		    if(is_file($adminValidatePath)) unlink($adminValidatePath);

		    // 4、删除后台模板文件
		    $adminTempPath = $modulePath.'view'.DS.$tabledir;
		    if(is_dir($adminTempPath)) $dofile->delDirAndFile($adminTempPath,true);
			
		    // 5、删除前台控制器文件
		    $indexControllerPath = $appPath.$this->lang.DS.'controller'.DS.$tabledir.'.php';
		    if(is_file($indexControllerPath)) unlink($indexControllerPath);

            // 加载前端配置文件
            $langConfig = app()->getBasePath().$this->lang.DS.'config'.DS.'template.php';
            $configArray = include_once($langConfig);

		    // 6、删除前台模板文件
		    $indexPcTempPath = $rootPath.'template'.DS.$configArray['theme'].DS.'pc'.DS.$tabledir;
		    $indexMobileTempPath = $rootPath.'template'.DS.$configArray['theme'].DS.'mobile'.DS.$tabledir;
		    if(is_dir($indexPcTempPath)) $dofile->delDirAndFile($indexPcTempPath,true);
		    if(is_dir($indexMobileTempPath)) $dofile->delDirAndFile($indexMobileTempPath,true);

		    // 7、删除对应的数据表
		    $moduleTable = config('database.connections.mysql.prefix').$tabledir;
		    Db::query("drop table if exists $moduleTable");
            /*删除其他信息 结束*/

            /*删除相关数据 开始*/
            // 删除广告
            $adWhere[] = ['lang','=',$this->lang]; $adWhere[] = ['position','=',$tabledir];
            Db::name('ad')->where($adWhere)->delete();
            // 删除属性
            $attWhere[] = ['lang','=',$this->lang]; $attWhere[] = ['tabledir','=',$tabledir];
            Db::name('attribute')->where($attWhere)->delete();
            // 删除分类
            $sortWhere[] = ['lang','=',$this->lang]; $sortWhere[] = ['tabledir','=',$tabledir];
            Db::name('sort')->where($sortWhere)->delete();
            /*删除相关数据 结束*/

            $deleteid[] = $id;
	    }

        try {
            Db::name('module')->delete($deleteid);
            return json(['code' => 200, 'msg' => lang('c_success'), 'data' => array('deleteid'=>$deleteid)]);
        } catch (Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage(), 'data' => '']);
        }
    }	

	// 更新启用
    public function update_disabled(){
	    $id = input('id'); $value = input('value');
		
		$moduleCountWhere[] = ['disabled','=',1]; $moduleCountWhere[] = ['lang','=',$this->lang];
	    $CountDisabled = Db::name('module')->where($moduleCountWhere)->count();
	    $RsDisabled = moduleModel::find($id);
	    if($value == 0 and $RsDisabled['disabled'] == 1 and $CountDisabled < 2){
            return json(['code' => 1001, 'msg' => lang('c_atleast_enable'), 'data' => '']);
        }

	    try {
            $RsDisabled->id = $id;
            $RsDisabled->disabled = $value;
            $RsDisabled->save();
            return json(['code' => 200, 'msg' => lang('c_success'), 'data' => array('id'=>$id)]);
        } catch (Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage(), 'data' => '']);
        }
	}

	// 批量更新
    public function update_all(){
		$id = input('id/a'); $seotitle = input('seotitle/a'); $keyword = input('keyword/a'); $description = input('description/a');
       
		foreach($id as $i => $rs){
            // $data[] = ['id'=>$id[$i],'seotitle'=>$seotitle[$i],'keyword'=>$keyword[$i],'description'=>$description[$i]];
            $data = ['id'=>$id[$i],'seotitle'=>$seotitle[$i],'keyword'=>$keyword[$i],'description'=>$description[$i]];
            Db::name('module')->update($data);
        }
        
        // $module = new moduleModel;
		// $module->saveAll($data,true);
		return json(['code' => 200, 'msg' => lang('c_success'), 'data' => '']);
    }

    // 单条删除模块表数据
    public function table_delete_one(){
        $id = input('id'); $tabledir = input('tabledir');
        // 含有模块禁止删除的信息
        $nodeleteidArr = explode(',', $this->navModuleRs['no_deleteid']);
        if(in_array($id, $nodeleteidArr)){
            return json(['code' => 1001, 'msg' => lang('c_nodeleteid_error'), 'data' => array('id'=>$id)]);
        }
        
        // 禁止删除含有子类的父类
        $moduleRs = Db::name($tabledir)->where('id','>',0)->find();
        if($moduleRs['module'] == 'About'){// 单页模型
            $hasChild = Db::name($tabledir)->where('parentid',$id)->find();
            if(!empty($hasChild)){
                return json(['code' => 1002, 'msg' => lang('c_delete_sort_child_first'), 'data' => array('id'=>$id)]);
            }
        }
        
        try {
            // 调用common.php函数删除
            ModuleDeleteOne($tabledir,$id,$this->lang);
            return json(['code' => 200, 'msg' => lang('c_success'), 'data' => array('id'=>$id)]);
        } catch (Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage(), 'data' => '']);
        }
    }

    // 批量删除模块表数据
    public function table_delete_all(){
        $selectid = input('selectid/a'); $tabledir = input('tabledir');
        // 请选择要删除的数据
        if(empty($selectid)){
            return json(['code' => 1001, 'msg' => lang('c_delete_check'), 'data' => array('selectid'=>$selectid)]);
        }
        // 含有模块禁止删除的信息
        $nodeleteidArr = explode(',', $this->navModuleRs['no_deleteid']);
        foreach ($selectid as $infoid) {
            if(in_array($infoid, $nodeleteidArr)){
                return json(['code' => 1002, 'msg' => lang('c_nodeleteid_error'), 'data' => array('selectid'=>$selectid)]);
            }
            break;
        }
        // 禁止删除含有子类的父类
        $moduleRs = Db::name($tabledir)->where('id','>',0)->find();
        if($moduleRs['module'] == 'About'){// 单页模型
            foreach($selectid as $i => $rs){
                $id = $selectid[$i];
                $hasChild = Db::name($tabledir)->where('parentid',$id)->find();
                if(!empty($hasChild)){
                    return json(['code' => 1003, 'msg' => lang('c_delete_sort_child_first'), 'data' => '']);
                    break;
                }
            }
        }

        try {
            // 调用common.php函数删除
            ModuleDeleteAll($tabledir,$selectid,$this->lang);
            return json(['code' => 200, 'msg' => lang('c_success'), 'data' => array('selectid'=>$selectid)]);
        } catch (Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage(), 'data' => '']);
        }
    }

    // 批量更新模块表数据
    public function table_update_all(){
        $id = input('id/a'); $title = input('title/a'); $sequence = input('sequence/a'); $tabledir = input('tabledir');
        // 参数不能为空
        if(empty($id) or empty($title) or empty($sequence)){
            return json(['code' => 1001, 'msg' => lang('c_error_parameter'), 'data' => array('id'=>$id)]);
        }

        foreach($id as $i => $rs){
            if(is_numeric($sequence[$i])){
                Db::name($tabledir)->update(['id'=>$id[$i],'title'=>$title[$i],'sequence'=>$sequence[$i]]);
            }
        }
        return json(['code' => 200, 'msg' => lang('c_success'), 'data' => '']);
    }

    /*单个更新模块表的signid标记：1上架2下架9软删除
    * 返回json值：
    * error:forbid含有模块禁止删除的信息
    * error:param参数错误
    * success成功
    */
    public function table_update_signid(){
        // 转为小写字母
        $general = new \common\General();
        $tabledir = $general->capital_to_underline(input('tabledir'));

        $id = input('id'); $signid = input('signid');
        // 参数不能为空
        if(empty($id) or empty($signid) or empty($tabledir)){
            return json(['code' => 1001, 'msg' => lang('c_error_parameter'), 'data' => array('id'=>$id)]);
        }
        
        // 含有模块禁止删除的信息
        $nodeleteidArr = explode(',', $this->navModuleRs['no_deleteid']);
        if(in_array($id, $nodeleteidArr)){
            return json(['code' => 1002, 'msg' => lang('c_nodeleteid_error'), 'data' => array('id'=>$id)]);
        }
        
        // 软删除
        if($signid == 9) $signid = time();

        try {
            Db::name($tabledir)->where('id',$id)->update(['signid'=>$signid]);
            return json(['code' => 200, 'msg' => lang('c_success'), 'data' => array('id'=>$id)]);
        } catch (Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage(), 'data' => '']);
        }
    }

    // 批量更新模块表的signid标记：1上架2下架9软删除
    public function table_update_all_signid(){
        // 转为小写字母
        $general = new \common\General();
        $tabledir = $general->capital_to_underline(input('tabledir'));
        
        $selectid = input('selectid/a'); $signid = input('signid');
        // 参数错误
        if(empty($selectid) or empty($signid) or empty($tabledir)){
            return json(['code' => 1001, 'msg' => lang('c_delete_check'), 'data' => array('selectid'=>$selectid)]);
        }
        // 含有模块禁止删除的信息
        $nodeleteidArr = explode(',', $this->navModuleRs['no_deleteid']);
        foreach ($selectid as $infoid) {
            if(in_array($infoid, $nodeleteidArr)){
                return json(['code' => 1002, 'msg' => lang('c_nodeleteid_error'), 'data' => array('selectid'=>$selectid)]);
            }
            break;
        }
        // 软删除
        if($signid == 9) $signid = time();
        
        try {
            Db::name($tabledir)->where('id','in',$selectid)->update(['signid'=>$signid]);
            return json(['code' => 200, 'msg' => lang('c_success'), 'data' => array('selectid'=>$selectid)]);
        } catch (Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage(), 'data' => '']);
        }
    }
}